﻿<template>
  <div class="purchase-management">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2>采购订单管理</h2>
      <button @click="openAdd" class="btn-primary">新增采购单</button>
    </div>

    <!-- 搜索栏 -->
    <div class="search-panel">
      <div class="search-form">
        <div class="form-group">
          <label>订单号</label>
          <input 
            v-model="query.orderNo" 
            @keyup.enter="search" 
            placeholder="请输入订单号" 
            class="form-input"
          />
        </div>
        <div class="form-group">
          <label>供应商ID</label>
          <input 
            v-model="query.supplierId" 
            @keyup.enter="search" 
            placeholder="请输入供应商ID" 
            class="form-input"
          />
        </div>
        <div class="form-group">
          <label>状态</label>
          <select v-model="query.status" class="form-select">
            <option value="">全部</option>
            <option value="0">草稿</option>
            <option value="1">待审核</option>
            <option value="2">已完成</option>
            <option value="3">已取消</option>
          </select>
        </div>
        <button @click="search" class="btn-primary">搜索</button>
        <button @click="reset" class="btn-secondary">重置</button>
      </div>
    </div>

    <!-- 数据表格 -->
    <div class="data-panel">
      <div class="panel-header">
        <h3>采购订单列表</h3>
        <p>管理所有采购订单信息</p>
      </div>
      
      <div v-if="loading" class="loading">
        加载中...
      </div>
      
      <div v-else-if="list.length === 0" class="empty">
        暂无数据
      </div>
      
      <div v-else class="table-container">
        <table class="data-table">
          <thead>
            <tr>
              <th>订单号</th>
              <th>供应商ID</th>
              <th>创建人ID</th>
              <th>总金额</th>
              <th>状态</th>
              <th>创建时间</th>
              <th>操作</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="item in list" :key="item.id">
              <td>{{ item.orderNo || '-' }}</td>
              <td>{{ item.supplierId || '-' }}</td>
              <td>{{ item.creatorId || '-' }}</td>
              <td>{{ item.totalAmount || '0.00' }}</td>
              <td>
                <span :class="getStatusClass(item.status)">{{ getStatusText(item.status) }}</span>
              </td>
              <td>{{ formatDate(item.createTime) }}</td>
              <td class="action-cell">
                <button @click="viewDetail(item)" class="btn-view">查看</button>
                <button @click="editItem(item)" class="btn-edit">编辑</button>
                <button @click="submitForAudit(item)" :disabled="item.status !== 0" class="btn-submit">提交审核</button>
                <button @click="deleteItem(item)" class="btn-delete">删除</button>
              </td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>

    <!-- 分页 -->
    <div class="pagination">
      <button @click="prevPage" :disabled="pageNum === 1" class="btn-page">上一页</button>
      <span class="page-info">
        第 {{ pageNum }} 页，共 {{ Math.ceil(total / pageSize) }} 页，总计 {{ total }} 条
      </span>
      <button @click="nextPage" :disabled="pageNum * pageSize >= total" class="btn-page">下一页</button>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { apiGet, apiPost, apiDelete } from '../../utils/api.js'

// 响应式数据
const loading = ref(false)
const list = ref([])
const total = ref(0)
const pageNum = ref(1)
const pageSize = ref(10)

// 查询条件
const query = reactive({
  orderNo: '',
  supplierId: '',
  status: ''
})

// 表单数据
const form = reactive({
  id: null,
  supplierId: null,
  creatorId: null,
  remark: '',
  items: []
})

// 对话框状态
const showDialog = ref(false)
const showDetail = ref(false)
const isEdit = ref(false)
const detail = ref(null)

// 组件挂载
onMounted(() => {
  load()
})

// 加载数据
async function load() {
  loading.value = true
  try {
    const params = {
      pageNum: pageNum.value,
      pageSize: pageSize.value,
    }
    if (query.orderNo) params.orderNo = query.orderNo
    if (query.supplierId) params.supplierId = query.supplierId
    if (query.status !== '') params.status = query.status
    
    // 构建查询字符串
    const qs = new URLSearchParams(params).toString()
    const response = await apiGet(`/procure-service/purchase-order${qs ? '?' + qs : ''}`)
    
    console.log('API响应数据:', response)
    
    // 处理不同的响应结构
    let records = []
    let totalCount = 0
    
    if (response.data) {
      records = response.data.records || response.data.list || []
      totalCount = response.data.total || 0
    } else if (response.records) {
      records = response.records || []
      totalCount = response.total || 0
    } else if (Array.isArray(response)) {
      records = response
      totalCount = response.length
    }
    
    console.log('解析后的records:', records)
    console.log('解析后的total:', totalCount)
    
    list.value = records.map(r => ({ ...r, id: r.id != null ? String(r.id) : r.id }))
    total.value = totalCount
    
    console.log('处理后的数据:', list.value)
  } catch (error) {
    console.error('加载失败:', error)
    list.value = []
    total.value = 0
  } finally {
    loading.value = false
  }
}

function search() {
  pageNum.value = 1
  load()
}

function reset() {
  query.orderNo = ''
  query.supplierId = ''
  query.status = ''
  pageNum.value = 1
  load()
}

function prevPage() {
  if (pageNum.value > 1) {
    pageNum.value--
    load()
  }
}

function nextPage() {
  if (pageNum.value * pageSize.value < total.value) {
    pageNum.value++
    load()
  }
}

function openAdd() {
  isEdit.value = false
  Object.assign(form, {
    id: null,
    supplierId: null,
    creatorId: null,
    remark: '',
    items: []
  })
  showDialog.value = true
}

function editItem(item) {
  isEdit.value = true
  form.id = item.id
  form.supplierId = item.supplierId
  form.creatorId = item.creatorId
  form.remark = item.remark || ''
  form.items = item.items ? [...item.items] : []
  showDialog.value = true
}

function closeDialog() {
  showDialog.value = false
}

function addItem() {
  form.items.push({
    productId: null,
    quantity: 1,
    price: 0,
    remark: ''
  })
}

function removeItem(index) {
  form.items.splice(index, 1)
}

async function submit() {
  // 验证必填字段
  if (!form.supplierId || !form.creatorId) {
    alert('请填写必填项：供应商ID、创建人ID')
    return
  }
  
  // 验证商品明细
  if (form.items.length === 0) {
    alert('请至少添加一条商品明细')
    return
  }
  
  for (let i = 0; i < form.items.length; i++) {
    const item = form.items[i]
    if (!item.productId || !item.quantity || !item.price) {
      alert(`第${i + 1}条商品明细信息不完整`)
      return
    }
  }
  
  try {
    const data = {
      supplierId: Number(form.supplierId),
      creatorId: Number(form.creatorId),
      remark: form.remark || '',
      items: form.items.map(item => ({
        productId: Number(item.productId),
        quantity: Number(item.quantity),
        price: Number(item.price),
        remark: item.remark || ''
      }))
    }
    
    if (isEdit.value) {
      // 由于后端没有更新接口，先删除再创建
      await apiDelete(`/procure-service/purchase-order/${form.id}`)
      await apiPost('/procure-service/purchase-order/create', data)
    } else {
      await apiPost('/procure-service/purchase-order/create', data)
    }
    
    alert(isEdit.value ? '更新成功' : '创建成功')
    closeDialog()
    load()
  } catch (error) {
    console.error('提交失败:', error)
    alert('提交失败：' + (error.message || '未知错误'))
  }
}

// 提交审核功能
async function submitForAudit(item) {
  if (!confirm(`确认提交订单【${item.orderNo}】进行审核吗？`)) {
    return
  }
  
  try {
    await apiPost(`/procure-service/purchase-order/${item.id}/submit`)
    alert('提交审核成功')
    load()
  } catch (error) {
    console.error('提交审核失败:', error)
    alert('提交审核失败：' + (error.message || '未知错误'))
  }
}

async function deleteItem(item) {
  if (!confirm(`确定删除订单【${item.orderNo}】吗？`)) {
    return
  }
  
  try {
    await apiDelete(`/procure-service/purchase-order/${item.id}`)
    alert('删除成功')
    load()
  } catch (error) {
    console.error('删除失败:', error)
    alert('删除失败：' + (error.message || '未知错误'))
  }
}

function viewDetail(item) {
  detail.value = item
  showDetail.value = true
}

function closeDetail() {
  showDetail.value = false
  detail.value = null
}

function getStatusText(status) {
  const statusMap = {
    0: '草稿',
    1: '待审核',
    2: '已完成',
    3: '已取消'
  }
  return statusMap[status] || '未知'
}

function getStatusClass(status) {
  const classMap = {
    0: 'status-draft',
    1: 'status-pending',
    2: 'status-completed',
    3: 'status-cancelled'
  }
  return classMap[status] || 'status-unknown'
}

function formatDate(dateString) {
  if (!dateString) return '-'
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}
</script>

<style scoped>
.purchase-management {
  padding: 20px;
  background: #f5f5f5;
  min-height: 100vh;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  color: #333;
  font-size: 24px;
  font-weight: 600;
}

.search-panel {
  background: #fff;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.search-form {
  display: flex;
  gap: 15px;
  align-items: center;
  flex-wrap: wrap;
}

.form-group {
  display: flex;
  align-items: center;
  gap: 8px;
}

.form-group label {
  color: #666;
  font-size: 14px;
  white-space: nowrap;
}

.form-input, .form-select {
  padding: 8px 12px;
  border: 1px solid #dcdfe6;
  border-radius: 6px;
  font-size: 14px;
}

.form-input {
  width: 200px;
}

.form-select {
  width: 120px;
}

.btn-primary {
  padding: 8px 16px;
  border: 1px solid #3b82f6;
  border-radius: 6px;
  background: #3b82f6;
  color: #fff;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.3s;
}

.btn-primary:hover {
  background: #2563eb;
}

.btn-secondary {
  padding: 8px 16px;
  border: 1px solid #dcdfe6;
  border-radius: 6px;
  background: #fff;
  color: #666;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.3s;
}

.btn-secondary:hover {
  background: #f8f9fa;
}

.data-panel {
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.panel-header {
  padding: 20px;
  border-bottom: 1px solid #ebeef5;
}

.panel-header h3 {
  margin: 0;
  color: #333;
  font-size: 18px;
  font-weight: 600;
}

.panel-header p {
  margin: 5px 0 0 0;
  color: #666;
  font-size: 14px;
}

.loading, .empty {
  padding: 40px;
  text-align: center;
  color: #666;
  font-size: 16px;
}

.table-container {
  overflow-x: auto;
}

.data-table {
  width: 100%;
  border-collapse: collapse;
  font-size: 14px;
}

.data-table th {
  padding: 12px;
  text-align: left;
  border-bottom: 1px solid #ebeef5;
  color: #666;
  background: #f8f9fa;
  font-weight: 600;
  white-space: nowrap;
}

.data-table td {
  padding: 12px;
  border-bottom: 1px solid #f0f0f0;
  color: #333;
}

.action-cell {
  white-space: nowrap;
}

.btn-view {
  padding: 4px 8px;
  border: 1px solid #909399;
  border-radius: 4px;
  background: #fff;
  color: #909399;
  cursor: pointer;
  margin-right: 8px;
  font-size: 12px;
  transition: all 0.3s;
}

.btn-view:hover {
  background: #909399;
  color: #fff;
}

.btn-edit {
  padding: 4px 8px;
  border: 1px solid #67c23a;
  border-radius: 4px;
  background: #fff;
  color: #67c23a;
  cursor: pointer;
  margin-right: 8px;
  font-size: 12px;
  transition: all 0.3s;
}

.btn-edit:hover {
  background: #67c23a;
  color: #fff;
}

.btn-submit {
  padding: 4px 8px;
  border: 1px solid #e6a23c;
  border-radius: 4px;
  background: #fff;
  color: #e6a23c;
  cursor: pointer;
  margin-right: 8px;
  font-size: 12px;
  transition: all 0.3s;
}

.btn-submit:hover:not(:disabled) {
  background: #e6a23c;
  color: #fff;
}

.btn-submit:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.btn-delete {
  padding: 4px 8px;
  border: 1px solid #f56c6c;
  border-radius: 4px;
  background: #fff;
  color: #f56c6c;
  cursor: pointer;
  margin-right: 8px;
  font-size: 12px;
  transition: all 0.3s;
}

.btn-delete:hover {
  background: #f56c6c;
  color: #fff;
}

.status-draft {
  color: #909399;
  background: #f4f4f5;
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 12px;
}

.status-pending {
  color: #e6a23c;
  background: #fdf6ec;
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 12px;
}

.status-completed {
  color: #67c23a;
  background: #f0f9ff;
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 12px;
}

.status-cancelled {
  color: #f56c6c;
  background: #fef0f0;
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 12px;
}

.status-unknown {
  color: #909399;
  background: #f4f4f5;
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 12px;
}

.pagination {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top: 20px;
  gap: 10px;
}

.btn-page {
  padding: 8px 12px;
  border: 1px solid #dcdfe6;
  border-radius: 6px;
  background: #fff;
  cursor: pointer;
  color: #666;
  font-size: 14px;
  transition: all 0.3s;
}

.btn-page:hover:not(:disabled) {
  background: #f8f9fa;
}

.btn-page:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.page-info {
  color: #666;
  font-size: 14px;
}
</style>
